import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';

export interface Task {
  id: string;
  name: string;
  type: 'convert' | 'compress' | 'extract_audio' | 'batch';
  status: 'queued' | 'processing' | 'completed' | 'failed' | 'paused';
  progress: number;
  eta: string;
  startTime: Date;
  estimatedDuration: number; // in seconds
  fileSize: number; // in bytes
  currentPhase: string;
  error?: string;
}

export const useActiveTasks = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchActiveTasks = async () => {
      try {
        // 模拟获取活跃任务
        const mockTasks: Task[] = [
          {
            id: '1',
            name: '视频压缩_sample.mp4',
            type: 'compress',
            status: 'processing',
            progress: 65,
            eta: '2分钟',
            startTime: new Date(Date.now() - 15 * 60 * 1000), // 15分钟前开始
            estimatedDuration: 1380, // 23分钟
            fileSize: 1024 * 1024 * 200, // 200MB
            currentPhase: '编码视频',
          },
          {
            id: '2',
            name: '格式转换_demo.avi',
            type: 'convert',
            status: 'queued',
            progress: 0,
            eta: '等待中',
            startTime: new Date(),
            estimatedDuration: 720, // 12分钟
            fileSize: 1024 * 1024 * 150, // 150MB
            currentPhase: '等待开始',
          },
          {
            id: '3',
            name: '音频提取_music.mov',
            type: 'extract_audio',
            status: 'completed',
            progress: 100,
            eta: '已完成',
            startTime: new Date(Date.now() - 30 * 60 * 1000), // 30分钟前开始
            estimatedDuration: 300, // 5分钟
            fileSize: 1024 * 1024 * 80, // 80MB
            currentPhase: '完成',
          },
        ];

        setTasks(mockTasks);
        setIsLoading(false);
      } catch (err) {
        setError('获取活跃任务失败');
        setIsLoading(false);
      }
    };

    fetchActiveTasks();

    // 模拟实时进度更新
    const progressInterval = setInterval(() => {
      setTasks(prevTasks =>
        prevTasks.map(task => {
          if (task.status === 'processing' && task.progress < 100) {
            const progressIncrement = Math.random() * 5;
            const newProgress = Math.min(100, task.progress + progressIncrement);
            
            // 根据进度更新阶段
            let currentPhase = task.currentPhase;
            if (newProgress < 25) currentPhase = '准备文件';
            else if (newProgress < 50) currentPhase = '分析视频';
            else if (newProgress < 75) currentPhase = '编码视频';
            else if (newProgress < 95) currentPhase = '处理音频';
            else currentPhase = '完成处理';

            return {
              ...task,
              progress: newProgress,
              currentPhase,
            };
          }
          return task;
        })
      );
    }, 3000);

    return () => clearInterval(progressInterval);
  }, []);

  const pauseTask = async (taskId: string) => {
    try {
      setTasks(prevTasks =>
        prevTasks.map(task =>
          task.id === taskId && task.status === 'processing'
            ? { ...task, status: 'paused' }
            : task
        )
      );
    } catch (err) {
      setError('暂停任务失败');
    }
  };

  const resumeTask = async (taskId: string) => {
    try {
      setTasks(prevTasks =>
        prevTasks.map(task =>
          task.id === taskId && task.status === 'paused'
            ? { ...task, status: 'processing' }
            : task
        )
      );
    } catch (err) {
      setError('恢复任务失败');
    }
  };

  const cancelTask = async (taskId: string) => {
    try {
      setTasks(prevTasks =>
        prevTasks.map(task =>
          task.id === taskId
            ? { ...task, status: 'failed', error: '用户取消' }
            : task
        )
      );
    } catch (err) {
      setError('取消任务失败');
    }
  };

  const removeTask = async (taskId: string) => {
    try {
      setTasks(prevTasks => prevTasks.filter(task => task.id !== taskId));
    } catch (err) {
      setError('移除任务失败');
    }
  };

  return {
    tasks,
    isLoading,
    error,
    pauseTask,
    resumeTask,
    cancelTask,
    removeTask,
  };
};